<?php
/**
 * Created by IntelliJ IDEA.
 * User: xingshi
 * Date: 16/7/20
 * Time: 下午2:16
 */

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use App\Judgetask;

//use Illuminate\Foundation\Inspiring;

class Judge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'judge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'judge the task';

    /**
     * Execute the console command.
     *
     * @return mixed
     */

    public function getLimit($taskid){
        return array("timelimit" => 10000, "memlimit" => 819200);
    }

    public function handle()
    {
//        select * from judgetasks where status=0 order by created_at asc limit 1;
//        python /opt/jail3/home/ql/onlinejudge/command.py 143 elf py 10000 819200
        while(true) {
            usleep(1000000);
            $judgetask = Judgetask::whereStatus(0)->orderby("created_at", "asc")->get()->first();
            if (empty($judgetask)) {
                continue;
            }
            try {
//              $userdir = md5($Judgetask->userid."+1s");
                $userdir = "elf";
                $path = "/opt/jail3/home/ql/onlinejudge/" . $judgetask->taskid . "/users/" . $userdir . "/Answer." . $judgetask->lan;
                $myfile = fopen($path, "w");
                fwrite($myfile, $judgetask->code);
                fclose($myfile);

                $limit = $this->getLimit($judgetask->taskid);
                $cmd = "python /opt/jail3/home/ql/onlinejudge/command.py " . $judgetask->taskid . " " . $userdir .
                    " " . $judgetask->lan . " " . $limit["timelimit"] . " " . $limit["memlimit"];

                $res = exec($cmd, $output);
                $data = json_decode($output[0], true);
                unset($output);
                $limit_len = 200;
                foreach ($data as $k => $v) {
                    if (strlen($k) > $limit_len || strlen($v) > $limit_len) {
                        unset($data[$k]);
                        $k = substr($k, 0, $limit_len);
                        $v = substr($v, 0, $limit_len);
                        $data[$k] = $v;
                    }
                }
                $judgetask->judge_info = json_encode($data);
            } catch (Exception $e) {
                //执行错误
                $judgetask->status = 2;
            }
            //正确执行完成
            $judgetask->status = 1;
            $judgetask->save();

        }

    }
}